import logger from '../lib/Log4js';
import * as rp from 'request-promise';
import env from './../config/env';
import dTalkApiUtil from 'dingtalk-app/dtalk/dTalkApiUtil';
import * as moment from 'moment';

export class DTalkApi {

    //获取部门详情
    async getDeptDetail(id: String,ACCESS_TOKEN:String) {
        let json = await rp.get(`https://oapi.dingtalk.com/department/get?access_token=${ACCESS_TOKEN}&id=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            return null
        }
    }

    //获取部门下的所有员工
    async getUserList(id: String,ACCESS_TOKEN:String) {
        let json = await rp.get(`https://oapi.dingtalk.com/user/simplelist?access_token=${ACCESS_TOKEN}&department_id=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            console.log('getUserList_error',json)
            throw json.errmsg;
        }
    }
    //获取员工详情
    async getUserDetail(id: String,ACCESS_TOKEN:String) {
        let json = await rp.get(`https://oapi.dingtalk.com/user/get?access_token=${ACCESS_TOKEN}&userid=${id}`,
            { json: true });
           // console.log(json,'json_json_json_json_json_json_json_')
        if (json.errcode === 0) {
            return json;
        } else {
            return null
        }
    }

    //根据员工的工号jobnumber获取钉钉通讯录,得到员工id
    async getDingDingAdressList(character: string,ACCESS_TOKEN:String) {
        let json = await rp.post('https://eco.taobao.com/router/rest',
            {
                //发起的审批实例----参数
                form: {
                    format: "json",
                    v: "2.0",   //api协议版本
                    timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),//时间戳
                    session: ACCESS_TOKEN,//钉钉提供的授权token
                    partner_id: "apidoc",   //合作伙伴身份标识
                    method: "dingtalk.corp.emp.search",//接口名称
                    offset: 0,
                    size: 100,
                    keyword: character
                }, json: true
            });

            if(json.dingtalk_corp_emp_search_response && json.dingtalk_corp_emp_search_response.result )
                return JSON.parse(json.dingtalk_corp_emp_search_response.result);
    }

    //批量获取员工一天的签到数据
    async getCheckInData_oneDay(userIdList: string[],access_token:string) {
        let date1 = moment().format('YYYY-MM-DD 00:00:00');
        let date2 = moment().format('YYYY-MM-DD 20:59:59');
        let satrt_time = new Date(date1).getTime();
        let end_time = new Date(date2).getTime();
        let month = moment().format('MM');
       let dataCache:any=[]
        for (let index = 0; index < userIdList.length; index++) {
            let element = userIdList[index];
            if(!dataCache[element]){
                dataCache[element]={
                   userId:element,
                   data:''
                }
            }
            let json = await rp.post('https://eco.taobao.com/router/rest',
            {
                form: {
                    format: "json",
                    session: access_token,//钉钉提供的授权token
                    timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),//时间戳
                    v: "2.0",   //api协议版本
                    partner_id: "apidoc",   //合作伙伴身份标识
                    method: "dingtalk.smartwork.checkin.record.get",//接口名称
                    start_time: satrt_time,
                    end_time: end_time,
                    cursor: 0,
                    size: 40,
                    userid_list: element
                }, json: true
            });
            //console.log(json,'<-------json')
            if (json.dingtalk_smartwork_checkin_record_get_response.result.success) {
                if(json.dingtalk_smartwork_checkin_record_get_response.result.result.page_list.checkin_record_vo){
                    let data=json.dingtalk_smartwork_checkin_record_get_response.result.result.page_list.checkin_record_vo[0] 
                    dataCache[element]={
                        userId:element,
                        data:data
                    }
                }else{
                    dataCache[element]={
                        userId:element,
                        data:''
                    }
                }
            } else {
                dataCache[element]={
                    userId:element,
                    data:''
                }
                logger.errorLogger().error(json.error_response);
            }
        }
        let list:any[]=[]       
         for (const key in dataCache) { //移植dataCache当中的属性到list当中
            if (dataCache.hasOwnProperty(key)) {
                const element = dataCache[key];
                list.push(element)
            }
        }
        return list
    }
    //获取所有子部门的id列表
    async getSondepIdList(id: String, fetch_child:boolean,ACCESS_TOKEN:String) {
        let json = await rp.get(`https://oapi.dingtalk.com/department/list?access_token=${ACCESS_TOKEN}&id=${id}&fetch_child=${fetch_child}`,
            { json: true });
        if (json.errcode === 0) {
            let deptData: number[] = []
            let detpNames: string[] = []
            let dept:any[]=[]
            json.department.map(item => {
                deptData.push(item.id)
                detpNames.push(item.name)
                dept.push({
                   id: item.id,//部门id
                    name:item.name//部门名称
                })
            })
            return { department: deptData, deptNames: detpNames ,dept:dept}
        } else {
            console.log('getSondepIdList_Error',json)
            throw json.errmsg;
        }
    }

    //获取部门列表
    async deptList(ACCESS_TOKEN:String) {
        let json = await rp.get(`https://oapi.dingtalk.com/department/list?access_token=${ACCESS_TOKEN}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            console.log('deptList_Error',json)
            return json.errmsg;
        }
    }

    async deptList2(id: String,ACCESS_TOKEN:string) {
        let json = await rp.get(`https://oapi.dingtalk.com/department/list?access_token=${ACCESS_TOKEN}&id=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            console.log('deptList2_Error',json)
            throw json.errmsg;
        }
    }

    //查询指定用户的所有上级父部门路径
    async list_parent_depts(userid: string,access_token:string) {
        let json = await rp.get(`https://oapi.dingtalk.com/department/list_parent_depts?access_token=${access_token}&userId=${userid}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            console.log('list_parent_depts_Error',json)
            throw json.errmsg;
        }
    }
    //查询部门的所有上级父部门路径
    async get_parent(id: number,ACCESS_TOKEN:String) {
        let json = await rp.get(`https://oapi.dingtalk.com/department/list_parent_depts_by_dept?access_token=${ACCESS_TOKEN}&id=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            console.log('get_parent_Error',json)
            throw json.errmsg;
        }
    }


    //获取部门成员详情
    async getDeptEmplDetail(id: String,ACCESS_TOKEN:String) {
        let json = await rp.get(`https://oapi.dingtalk.com/user/list?access_token=${ACCESS_TOKEN}&department_id=${id}`,
            { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            console.log('部门id:',id,'getDeptEmplDetail_Error===>',json)
            throw json.errmsg;
        }    
    }

    //获取部门下的用户id列表  //:https://oapi.dingtalk.com/user/getDeptMember?access_token=ACCESS_TOKEN&deptId=1
    async getDeptMembers(depteid:string,access_token:string){
        let json = await rp.get(`https://oapi.dingtalk.com/user/getDeptMember?access_token=${access_token}&deptId=${depteid}`,
        { json: true });
        if (json.errcode === 0) {
            return json;
        } else {
            console.log('部门id:',depteid,'getDeptMembers_Error===>',json)
            return null;
        }
    }









  

}
let dTalkApi = new DTalkApi();
export default dTalkApi;

